var app = getApp()
var baseUrl = app.globalData.baseUrl
Page({
  data: {
    userInfo: null,
    hasUser: false,
    openid: ''
  },
  onShow(option) {
    try {
      let user = wx.getStorageSync('userInfo')
      if (user) {
        this.setData({
          userInfo: user,
          hasUser: true
        })
        console.log(user)
      }
    } catch (e) {
      console.log('获取缓存失败', e)
    }

  },
  getOpenid() {
    wx.cloud.callFunction({
      name: 'get',
      complete: res => {
        let openid = res.result.openid;
        this.setData({
          openid: openid
        })
      }
    })
  },

  login() {
    this.getOpenid()
    wx.getUserProfile({
      desc: '获取用户信息',
      success: res => {
        var user = res.userInfo
        let user_openid = this.data.openid
        //设置局部用户信息
        this.setData({
          userInfo: user,
          hasUser: true
        })
        //检查数据库是否有该用户
        wx.request({
          url: baseUrl+'user/getUserInfo/'+user_openid,
          method:'GET',
          success: res => {
            console.log(res)
            //原先没有添加，这里添加
            if (!res.data) {
              //将数据添加到数据库
              wx.request({
                url: baseUrl+'user/addUser',
                method: 'POST',
                data: {
                  avatarUrl: user.avatarUrl,
                  nickName: user.nickName,
                  _openid: user_openid
                },
                success: res => {
                  console.log(增加的用户)
                  if(res.data){
                    wx.setStorageSync('userInfo',res.data)
                  }
                }
            }) 
          }else{
            wx.setStorageSync('userInfo', res.data)
          }
        }
    })
    }
  })
  },
  logout(){
    wx.showModal({
      cancelColor: 'cancelColor',
      content: '是否注销？',
      success: (res)=>{
        if(res.confirm){
          this.setData({
            hasUser: false,
            userInfo: null
          })
          try{
            wx.removeStorageSync('userInfo')
          }
          catch(e){
          }
        }
      }
    })
  },
  toAddress() {
    wx.navigateTo({
      url: '/pages/address/address',
    })
  },
  //我发布的
  publisher() {
    wx.navigateTo({
      url: '/pages/publishs/publishs',
    })
  },
  //我参与的
  myAuction() {
    wx.navigateTo({
      url: '/pages/participates/participates',
    })
  },
  //交易记录
  myDeal() {
    wx.navigateTo({
      url: '/pages/myDeal/myDeal',
    })
  },
  //个人动态
  myarticle(){
    wx.navigateTo({
      url: '/pages/myArticle/myarticle',
    })
  },
  itemMag(){
    wx.navigateTo({
      url: '/pages/itemMag/itemMag',
    })
  },
  //问题反馈
  feedback(){
    wx.navigateTo({
      url: '/pages/feedback/feedback',
    })
  },
})